import json
import os

import requests

from installation_make_package_conf import teamcity_host_url, teamcity_psw, teamcity_user, artifacts_conf_map, \
    package_folder_path, get_package_name, need_copy_to_remote, dst_user_name, dst_ip, dst_port, \
    remote_package_folder_path, py_script_to_package
from instools import logger, md5_sum, cmd, copy_to_remote_host, cmd_remote_trust, check_file_exists


def query_tc_api(req_url):
    req = teamcity_host_url + req_url
    logger.info(req)
    header = {"Accept": "Application/JSON"}
    res = requests.get(req, auth=(teamcity_user, teamcity_psw), headers=header)
    if res.status_code != 200:
        raise Exception("%s: %s" % (res.reason, res.text))
    logger.info(res.text)
    return json.loads(res.text)


def query_build_id(build_type, build_number):
    url = '/httpAuth/app/rest/builds/?locator=buildType:{},number:{}'.format(build_type, build_number)
    bd = query_tc_api(url)
    if bd.get('count') != 1:
        raise Exception("query teamcity error, return count is not 1".format(url))
    return bd.get('build')[0].get('id')


def download_artifact(build_id, artifact_name, path_to_store):
    req_url = '/httpAuth/app/rest/builds/id:{}/artifacts/content/{}'.format(build_id, artifact_name)
    logger.info(req_url)
    req = teamcity_host_url + req_url
    with requests.get(req, auth=(teamcity_user, teamcity_psw), stream=True) as r:
        r.raise_for_status()
        with open(path_to_store, 'wb') as f:
            for chunk in r.iter_content(chunk_size=512 * 1024):
                f.write(chunk)
    md5_sum(path_to_store)
    return path_to_store


if __name__ == "__main__":
    file_list_to_remote = []
    for key in artifacts_conf_map.keys():
        build_type = key
        build_number = artifacts_conf_map[key].get('build_number')
        artifact_name = artifacts_conf_map[key].get('artifact_name')
        package_save_path = package_folder_path + '/' + get_package_name(key)
        logger.debug(package_save_path)
        cmd("mkdir -p %s" % package_folder_path)
        bd_id = query_build_id(build_type, build_number)
        file = download_artifact(bd_id, artifact_name, package_save_path)
        file_list_to_remote.append(file)

    for py_file in py_script_to_package:
        # script is also pick into folder
        cmd("cp -f  %s %s" % (py_file, package_folder_path))

    file_list_to_remote += py_script_to_package
    remote_copy_pair_log = []
    if need_copy_to_remote:
        cmd_remote_trust(dst_user_name, dst_ip, 'mkdir -p {}'.format(remote_package_folder_path))
        for file in file_list_to_remote:
            check_file_exists(file)
            dst_file_path = remote_package_folder_path + os.path.basename(file)
            copy_to_remote_host(file, dst_user_name, dst_ip, dst_file_path, cal_md5=True,
                                dst_port=dst_port)
            remote_copy_pair_log.append((file, dst_file_path))
        for log_item in remote_copy_pair_log:
            logger.debug(log_item)
        print("if run remote deployment,please enter 'woyaobushu'")
        passwd = input()
        if passwd == 'woyaobushu':
            cmd_remote_trust(dst_user_name, dst_ip,
                             '/usr/bin/python3 {}'.format(remote_package_folder_path + 'installation_deploy_package.py'))